import { defineStore } from 'pinia'
import { ref } from 'vue'
import { chatWithAI } from '../services/ai'

export const useChatStore = defineStore('chat', () => {
  const messages = ref([
    {
      role: 'system',
      content: '你是一个有帮助的AI助手，会根据上下文提供连贯的回答。'
    }
  ])
  const loading = ref(false)
  const currentStreamingMessage = ref('')

  const getMessageHistory = () => {
    return messages.value.map(msg => ({
      role: msg.role,
      content: msg.content
    }))
  }

  const addMessage = (role, content) => {
    messages.value.push({ role, content })
    saveHistory() // 每次添加消息后保存历史记录
  }

  const sendMessage = async (content) => {
    if (!content.trim()) return

    try {
      // 立即添加用户消息
      addMessage('user', content)
      
      // 设置加载状态
      loading.value = true
      currentStreamingMessage.value = ''

      let isFirstChunk = true
      
      // 发送消息给 AI
      const messageHistory = getMessageHistory()
      await chatWithAI(messageHistory, (chunk) => {
        if (isFirstChunk) {
          // 第一个响应时添加助手消息
          addMessage('assistant', '')
          isFirstChunk = false
        }
        
        currentStreamingMessage.value += chunk
        // 更新最后一条消息
        if (messages.value.length > 0) {
          messages.value[messages.value.length - 1].content = currentStreamingMessage.value
          saveHistory() // 保存每个更新
        }
      })

    } catch (error) {
      console.error('发送消息失败:', error)
      addMessage('system', '发送消息失败，请重试')
    } finally {
      loading.value = false
      currentStreamingMessage.value = ''
      saveHistory() // 确保最终状态被保存
    }
  }

  const clearHistory = () => {
    messages.value = [{
      role: 'system',
      content: '你是一个有帮助的AI助手，会根据上下文提供连贯的回答。'
    }]
    saveHistory()
  }

  const saveHistory = () => {
    try {
      localStorage.setItem('chatHistory', JSON.stringify(messages.value))
    } catch (error) {
      console.error('保存历史记录失败:', error)
    }
  }

  const loadHistory = () => {
    try {
      const savedHistory = localStorage.getItem('chatHistory')
      if (savedHistory) {
        const parsed = JSON.parse(savedHistory)
        if (Array.isArray(parsed) && parsed.length > 0) {
          messages.value = parsed
        } else {
          clearHistory()
        }
      }
    } catch (error) {
      console.error('加载历史记录失败:', error)
      clearHistory()
    }
  }

  return {
    messages,
    loading,
    currentStreamingMessage,
    sendMessage,
    clearHistory,
    saveHistory,
    loadHistory
  }
}) 